package tech.eyao.hs60x.user.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.enums.ExceptionCodeEnum;
import tech.eyao.hs60x.model.domain.AppVersionDO;
import tech.eyao.hs60x.service.AppVersionService;
import tech.eyao.hs60x.utils.RequestUtils;

@Api("系统设置相关")
@RequestMapping("/system")
@RestController
public class SystemConfigurationController {
    private static final Logger logger = LoggerFactory.getLogger(SystemConfigurationController.class);
    @Autowired
    private AppVersionService   appVersionServiceImpl;

    @GetMapping("/getTime.do")
    @ApiOperation(value = "获取服务端时间")
    public java.util.Date getSystemTime() {
        return new LocalDateTime().toDate();
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/appVersion.do", method = RequestMethod.POST)
    @ApiOperation(value = "系统升级提示,(_appid|_version)")
    public @ResponseBody BaseResult systemUpgrade() {
        //获取Header 存储的相关性信息
        try {
            String appId = RequestUtils.getRequest().getHeader(CommonConstants.APPID);
            String versionCode = RequestUtils.getRequest().getHeader(CommonConstants.APP_VERSION_CODE);
            if (StringUtils.isBlank(appId) || StringUtils.isBlank(versionCode)) {
                return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                        ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
            }
            BaseResult rs = appVersionServiceImpl.queryAppVersionByAppId(appId);
            if (null != rs && null != rs.getData()) {
                List<AppVersionDO> appVersinList = (List<AppVersionDO>) rs.getData();
                AppVersionDO appVersionDO = appVersinList.get(0);
                if (Integer.parseInt(versionCode) != appVersionDO.getVersionCode()) {
                    return BaseResult.isSuccess(appVersinList.get(0));
                }
                return BaseResult.isSuccess();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return BaseResult.isDeFaultFailure();
        }
        return BaseResult.isDeFaultNoData();
    }

}
